#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

using namespace std;

const int num = 5;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//条件变量
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//锁

void *active(void *args)
{
    string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);//线程开始等待。在调用时，会自动释放锁

        cout << name << "活动" << endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t tids[num];
    for (int i = 0; i < num; i++)
    {
        char *name = new char[32];
        snprintf(name, 32, "thread-%d", i + 1);
        pthread_create(tids + 1, nullptr, active, name);
    }
    sleep(3);

    while(true)//主线程逐个唤醒线程
    {
        cout<<"main thread wakeup thread"<<endl;
        pthread_cond_signal(&cond);
        //pthread_cond_broad(&cond);一次性唤醒所有线程
        sleep(1);
    }
    for (int i = 0; i < num; i++)
    {
        pthread_join(tids[i], nullptr);
    }
}